package com.deercrowing.takeaway.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.deercrowing.takeaway.common.constant.MessageConstant;
import com.deercrowing.takeaway.common.constant.StatusConstant;
import com.deercrowing.takeaway.common.exception.BusinessException;
import com.deercrowing.takeaway.context.BaseContext;
import com.deercrowing.takeaway.dao.DishFlavorMapper;
import com.deercrowing.takeaway.dao.DishesMapper;
import com.deercrowing.takeaway.dao.OrdersMapper;
import com.deercrowing.takeaway.dao.SetmealDishMapper;
import com.deercrowing.takeaway.entity.DishFlavorEntity;
import com.deercrowing.takeaway.entity.DishesEntity;
import com.deercrowing.takeaway.service.DishesService;
import com.deercrowing.takeaway.vo.DishesPageVO;
import com.deercrowing.takeaway.vo.DishesVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.time.YearMonth;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 菜品表(Dishes)表服务实现类
 *
 * @author guoyongxiang
 * @since 2024-07-11 10:50:59
 */
@Service
@Slf4j
public class DishesServiceImpl extends ServiceImpl<DishesMapper, DishesEntity> implements DishesService {

    @Autowired
    DishesMapper dishesMapper;

    @Autowired
    DishFlavorMapper dishFlavorMapper;

    @Autowired
    SetmealDishMapper setmealDishMapper;

    @Autowired
    OrdersMapper ordersMapper;

    @Override
    public void compareByContext(DishesVO dishesVO, Integer isAddOrUpdate) {
        Integer id = dishesVO.getId();
        String name = dishesVO.getName();

        List<DishesEntity> dsList = dishesMapper.selectList();
        if (isAddOrUpdate == 2) {
            for (DishesEntity dishEntity : dsList) {
                //  新增、修改实体类名称不能与相同分类下的其他实体类相同
                if (name.equals(dishEntity.getName()) && id != dishEntity.getId()) {
                    throw new BusinessException(MessageConstant.DISHNAME_ALREADY_EXISTS);
                }
            }
        }
        else {
            for (DishesEntity dishEntity : dsList) {
                //  新增、修改实体类名称不能与相同分类下的其他实体类相同
                if (name.equals(dishEntity.getName())) {
                    throw new BusinessException(MessageConstant.DISHNAME_ALREADY_EXISTS);
                }
            }
        }
    }

    @Override
    public void dishStatusUpdate(Short status, Integer id) {
        if (ObjectUtils.isEmpty(dishesMapper.selectById(id))) {
            throw new BusinessException(MessageConstant.DISHNAME_ALREADY_EXISTS);
        }

        dishesMapper.updateByStatus(status, id);
    }

    @Override
    public IPage<DishesVO> searchByCondition(DishesPageVO dishesPageVO) {
        int page = dishesPageVO.getPage() == null ? 1 : dishesPageVO.getPage();
        int pageSize = dishesPageVO.getPageSize() == null ? 10 : dishesPageVO.getPageSize();

        Integer limit = (page - 1) * pageSize;
        dishesPageVO.setPage(limit);
        dishesPageVO.setPageSize(pageSize);

        List<DishesEntity> dishesEntityList = dishesMapper.selectListByCondition(dishesPageVO);

        if (dishesEntityList.size() < 0){
            throw new BusinessException(MessageConstant.DISH_NOT_FOUND);
        }

        List<DishesVO> dishesVOList = dishesEntityList.stream()
                .map(source -> new DishesVO(
                        source.getId(),
                        source.getName(),
                        source.getCategoryId(),
                        source.getPrice(),
                        source.getImage(),
                        source.getStatus(),
                        source.getDescription(),
                        source.getUpdateTime(),
                        null,
                        null))
                .collect(Collectors.toList());

        Integer count = dishesMapper.countDishNum(dishesPageVO);

        IPage<DishesVO> entityPage = new Page<>(page,pageSize);
        entityPage.setRecords(dishesVOList);
        entityPage.setTotal(count);

        return entityPage;
    }

    @Override
    public List<DishesVO> selectDishWithFlavor(Short category_id) {
        List<DishesEntity> dishesEntityList = dishesMapper.selectListByCategory(category_id);
        List<DishesVO> dishesVOList = new ArrayList<>();

        if (dishesEntityList == null || dishesEntityList.size() < 0){
            throw new BusinessException(MessageConstant.DISH_NOT_FOUND);
        }

        // 设置单菜品月销量数据
        int countByDishSales = 0;
        YearMonth currentDate = YearMonth.from(LocalDateTime.now());
        Map<String,Object> dataMap = new HashMap<>();
        dataMap.put("begin",currentDate.atDay(1));
        dataMap.put("end",currentDate.atEndOfMonth());

        for (DishesEntity dishesEntity : dishesEntityList){
            DishesVO dishesVO = new DishesVO();
            BeanUtils.copyProperties(dishesEntity,dishesVO);

            dataMap.put("name",dishesEntity.getName());
            countByDishSales = ordersMapper.sumByDishSales(dataMap) == null ? 0 : ordersMapper.sumByDishSales(dataMap);
            dishesVO.setSales(countByDishSales);

            List<DishFlavorEntity> flavorEntityList = dishFlavorMapper.selectListByDishId(dishesEntity.getId());
            dishesVO.setFlavors(flavorEntityList);
            dishesVOList.add(dishesVO);
        }

        return dishesVOList;
    }

    @Override
    public Integer getDishId(String name) {
        Integer id = dishesMapper.selectIdByName(name);

        if(ObjectUtils.isEmpty(id)){
            throw new NullPointerException();
        }

        return id;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteDishWithFlavor(List<Integer> idList) {
        // 查询该分类是否被套餐关联
        List<Integer> setmealIdList = setmealDishMapper.selectBySetmealId(idList);
        if (setmealIdList.size() > 0){
            throw new BusinessException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        // 查询该分类是否是起售状态
        for (Integer id : idList){
            DishesEntity dishesEntity = dishesMapper.selectById(id);
            if (StatusConstant.ENABLE == dishesEntity.getStatus()){
                throw new BusinessException(MessageConstant.DISH_ON_SALE);
            }

            dishesMapper.deleteById(id);
            dishFlavorMapper.deleteByDishId(id.shortValue());
        }
    }

    @Override
    public DishesVO searchById(Long id) {
        DishesEntity dishesEntity = dishesMapper.selectById(id);

        if (ObjectUtils.isEmpty(dishesEntity)){
            throw new BusinessException("数据不存在");
        }

        DishesVO dishesVO = new DishesVO();
        List<DishFlavorEntity> dishFlavorEntity = dishFlavorMapper.selectListByDishId(id.intValue());
        BeanUtils.copyProperties(dishesEntity,dishesVO);

        dishesVO.setFlavors(dishFlavorEntity);

        return dishesVO;
    }

    @Override
    public void updateInfoToDB(Long id, DishesVO dishesVO) {
        DishesEntity entity = dishesMapper.selectById(id);

        if (ObjectUtils.isEmpty(entity)){
            throw new BusinessException(MessageConstant.DISH_NOT_FOUND);
        }

        // 对比菜品名称是否重复
        compareByContext(dishesVO,2);

        // 更新数据
        entity.setUpdateTime(LocalDateTime.now())
              .setUpdateEmployee(BaseContext.getCurrentId().intValue())
              .setDescription(dishesVO.getDescription())
              .setPrice(dishesVO.getPrice())
              .setCategoryId(dishesVO.getCategoryId())
              .setImage(dishesVO.getImage())
              .setName(dishesVO.getName())
              .updateById();

        // 删除口味
        dishFlavorMapper.deleteByDishId(dishesVO.getId().shortValue());

        //重新插入口味信息
        List<DishFlavorEntity> flavorEntityList = dishesVO.getFlavors();
        if (flavorEntityList != null && flavorEntityList.size() > 0) {
            flavorEntityList.forEach(dishFlavor -> {
                dishFlavor.setDishId(entity.getId());
            });
            //向口味表插入n条数据
            dishFlavorMapper.insertBatch(flavorEntityList);
        }
    }

    @Override
    public void insertInfoToDB(DishesVO dishesVO) {
        DishesEntity entity = new DishesEntity();
        BeanUtils.copyProperties(dishesVO,entity);

        // 对比菜品名称是否重复
        compareByContext(dishesVO,1);

        entity.setId(0)
              .setStatus(StatusConstant.DISABLE)
              .setCreateTime(LocalDateTime.now())
              .setUpdateTime(LocalDateTime.now())
              .setCreateEmployee(BaseContext.getCurrentId().intValue())
              .setUpdateEmployee(BaseContext.getCurrentId().intValue())
              .insert();

        Integer dish_Id = getDishId(entity.getName());

        List<DishFlavorEntity> flavorEntityList = dishesVO.getFlavors();
        if (flavorEntityList != null && flavorEntityList.size() > 0) {
            flavorEntityList.forEach(dishFlavor -> {
                dishFlavor.setDishId(dish_Id);
            });
            //向口味表插入n条数据
            dishFlavorMapper.insertBatch(flavorEntityList);
        }
    }
}

